// 需求管理API接口
import type { Requirement, GetRequirementsParams, RequirementStats } from '../types/requirement';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { requirementData } from '../data/requirementData';

// 需求API基础路径
const REQUIREMENT_API_BASE = `${getAPI_BASE_URL_SYNC()}/requirements`;

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 需求列表响应格式
interface RequirementListResponse {
  requirements: Requirement[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 需求模拟API实现
const mockRequirementApi = {
  async getRequirements(params: GetRequirementsParams = {}): Promise<ApiResponse<Requirement[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, category, project, status, priority } = params;
    
    // 过滤数据
    let filteredData = [...requirementData];
    
    if (search) {
      filteredData = filteredData.filter(req => 
        req.title.toLowerCase().includes(search.toLowerCase()) ||
        req.code.toLowerCase().includes(search.toLowerCase()) ||
        req.description.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (category) {
      filteredData = filteredData.filter(req => req.category === category);
    }
    
    if (project) {
      filteredData = filteredData.filter(req => req.project === project);
    }
    
    if (status) {
      filteredData = filteredData.filter(req => req.status === status);
    }
    
    if (priority) {
      filteredData = filteredData.filter(req => req.priority === priority);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取需求列表成功'
    };
  },

  async createRequirement(requirementData: Partial<Requirement>): Promise<ApiResponse<Requirement>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newRequirement: Requirement = {
      id: Date.now(),
      code: requirementData.code || `REQ-${Date.now().toString().slice(-3)}`,
      title: requirementData.title || '',
      description: requirementData.description || '',
      category: requirementData.category || '功能需求',
      project: requirementData.project || 'KZ-DevOps平台',
      status: requirementData.status || '规划中',
      priority: requirementData.priority || '中',
      submitter: requirementData.submitter || '',
      assignee: requirementData.assignee || '',
      progress: requirementData.progress || 0,
      deadline: requirementData.deadline || new Date().toISOString().split('T')[0],
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
      estimatedHours: requirementData.estimatedHours || 0,
      actualHours: requirementData.actualHours || 0,
      tags: requirementData.tags || [],
      attachments: requirementData.attachments || []
    };
    
    requirementData.push(newRequirement);
    
    return {
      data: newRequirement,
      total: 1,
      success: true,
      message: '需求创建成功'
    };
  },

  async updateRequirement(requirementId: number, requirementData: Partial<Requirement>): Promise<ApiResponse<Requirement>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = requirementData.findIndex(req => req.id === requirementId);
    if (index === -1) {
      throw new Error('需求不存在');
    }
    
    requirementData[index] = { 
      ...requirementData[index], 
      ...requirementData, 
      updatedAt: new Date().toISOString().split('T')[0] 
    };
    
    return {
      data: requirementData[index],
      total: 1,
      success: true,
      message: '需求信息更新成功'
    };
  },

  async deleteRequirement(requirementId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = requirementData.findIndex(req => req.id === requirementId);
    if (index === -1) {
      throw new Error('需求不存在');
    }
    
    requirementData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '需求删除成功'
    };
  },

  async getRequirementStats(): Promise<ApiResponse<RequirementStats>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const stats: RequirementStats = {
      total: requirementData.length,
      inProgress: requirementData.filter(req => 
        req.status === '设计中' || req.status === '开发中' || req.status === '测试中'
      ).length,
      completed: requirementData.filter(req => req.status === '已完成').length,
      highPriority: requirementData.filter(req => req.priority === '高' || req.priority === '紧急').length
    };
    
    return {
      data: stats,
      total: 1,
      success: true,
      message: '获取需求统计成功'
    };
  }
};

export const requirementApi = {
  // 获取需求列表（支持分页、搜索、筛选）
  async getRequirements(params: GetRequirementsParams = {}): Promise<ApiResponse<Requirement[]>> {
    if (shouldUseMockServer()) {
      return mockRequirementApi.getRequirements(params);
    }
    try {
      const { page = 1, pageSize = 10, search, category, project, status, priority } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (category) queryParams.append('category', category);
      if (project) queryParams.append('project', project);
      if (status) queryParams.append('status', status);
      if (priority) queryParams.append('priority', priority);
      
      const url = `${REQUIREMENT_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<RequirementListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 直接返回后端数据，不需要再次解包
        const requirementList = backendData.data as RequirementListResponse;
        return {
          data: requirementList.requirements || [],
          total: requirementList.total || 0,
          success: true,
          message: backendData.message || '获取需求列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取需求列表失败');
      }
    } catch (error) {
      console.error('获取需求列表失败:', error);
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取需求列表失败'
      };
    }
  },

  // 创建需求
  async createRequirement(requirementData: Partial<Requirement>): Promise<ApiResponse<Requirement>> {
    if (shouldUseMockServer()) {
      return mockRequirementApi.createRequirement(requirementData);
    }
    try {
      const response = await http.post<BackendApiResponse<Requirement>>(REQUIREMENT_API_BASE, requirementData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '需求创建成功'
        };
      } else {
        throw new Error(backendData.message || '需求创建失败');
      }
    } catch (error) {
      console.error('需求创建失败:', error);
      return {
        data: {} as Requirement,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '需求创建失败'
      };
    }
  },

  // 更新需求
  async updateRequirement(requirementId: number, requirementData: Partial<Requirement>): Promise<ApiResponse<Requirement>> {
    if (shouldUseMockServer()) {
      return mockRequirementApi.updateRequirement(requirementId, requirementData);
    }
    try {
      const url = `${REQUIREMENT_API_BASE}/${requirementId}`;
      const response = await http.put<BackendApiResponse<Requirement>>(url, requirementData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '需求信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '需求信息更新失败');
      }
    } catch (error) {
      console.error('需求信息更新失败:', error);
      return {
        data: {} as Requirement,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '需求信息更新失败'
      };
    }
  },

  // 删除需求
  async deleteRequirement(requirementId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockRequirementApi.deleteRequirement(requirementId);
    }
    try {
      const url = `${REQUIREMENT_API_BASE}/${requirementId}`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '需求删除成功'
        };
      } else {
        throw new Error(backendData.message || '需求删除失败');
      }
    } catch (error) {
      console.error('需求删除失败:', error);
      return {
        data: false,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '需求删除失败'
      };
    }
  },

  // 获取需求统计
  async getRequirementStats(): Promise<ApiResponse<RequirementStats>> {
    if (shouldUseMockServer()) {
      return mockRequirementApi.getRequirementStats();
    }
    try {
      const url = `${REQUIREMENT_API_BASE}/stats`;
      const response = await http.get<BackendApiResponse<RequirementStats>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取需求统计成功'
        };
      } else {
        throw new Error(backendData.message || '获取需求统计失败');
      }
    } catch (error) {
      console.error('获取需求统计失败:', error);
      return {
        data: {} as RequirementStats,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取需求统计失败'
      };
    }
  }
};